<?php

class wx{

    private $appId;

    private $appSecret;

    private $accToken=null;

    private $fansUser=[];

    function __construct($appid,$appSecret){
            $this->appId = $appid;
            $this->appSecret = $appSecret;
    }


    function getAccToken(){

        if($this->accToken!==null && $this->accToken['exp']>time()){
                return $this->accToken['val'];
        }

        $result =  file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appId."&secret=".$this->appSecret);

        $resultArr = json_decode( $result,true);
        if(isset($resultArr['errcode'])){ //包含错误
            throw new  Exception($resultArr['errmsg'],$resultArr['errcode']);
        }

        $this->accToken['val'] = $resultArr['access_token'];
        $this->accToken['exp'] = time()+intval($resultArr['expires_in']);
        return $this->accToken['val'];
    }

    function sendTplMsg($data){
        try {
            $accToken = $this->getAccToken();
            $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $accToken;
            return http_post_json($url, $data,true);
        }catch (Exception $e){
            echo $e->getMessage();
        }
    }

    function getFansUserList(){
            if(count($this->fansUser)){
                return $this->fansUser;
            }
            $accToken = $this->getAccToken();
            $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" . $accToken."&next_openid=";
            $result =  file_get_contents($url);
            $resultArr = json_decode( $result,true);
            if(isset($resultArr['errcode'])){ //包含错误
                throw new  Exception($resultArr['errmsg'],$resultArr['errcode']);
            }
            if($resultArr['count']==0){ //暂无关注
                throw new  Exception(400,"暂无关注人员");
            }
            $this->fansUser=$resultArr['data']['openid'];
            return $this->fansUser;
    }



}

